<template>
  <section class="todoapp">
    <my-header @add="handAdd"></my-header>
    <my-main
      :list="list2"
      @del="handDel"
      @state="handState"
      @changeAll="handAll"
    ></my-main>
    <my-footer
      :flag="flag"
      :list="list"
      @Purgecompleted="purge"
      @changeFlag="
        (val) => {
          flag = val;
        }
      "
    ></my-footer>
  </section>
</template>

<script>
import MyFooter from "./components/MyFooter.vue";
import MyHeader from "./components/MyHeader.vue";
import MyMain from "./components/MyMain.vue";
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem("my-list")) || [],
      // list: [
      //   { id: 12, name: "吃饭", isDone: false },
      //   { id: 14, name: "听歌", isDone: true },
      //   { id: 23, name: "洗澡", isDone: true },
      //   { id: 34, name: "睡觉", isDone: false },
      //   { id: 35, name: "游戏", isDone: false },
      // ],
      flag: 1, // 1 显示全部任务； 2 显示进行中； 3 显示已完成
    };
  },
  methods: {
    handDel(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    handAdd(todo) {
      // this.list.push(); //向数组末尾添加元素
      // this.list.unshift(); //向数组的开头添加元素
      this.list.unshift({
        id: +new Date(),
        name: todo,
        isDone: false,
      });
    },
    handState(id) {
      const row = this.list.find((item) => item.id === id);
      row.isDone = !row.isDone;
    },
    purge() {
      // isDone=true是已完成的,清除掉已完成的就是保留未完成的
      this.list = this.list.filter((item) => item.isDone === false);
    },
    handAll(val) {
      this.list.forEach((item) => (item.isDone = val));
    },
  },
  computed: {
    list2() {
      if (this.flag === 1) {
        return this.list;
      } else if (this.flag === 2) {
        return this.list.filter((item) => item.isDone === false);
      } else {
        return this.list.filter((item) => item.isDone);
      }
    },
  },
  watch: {
    list: {
      handler(val) {
        localStorage.setItem("my-list", JSON.stringify(val));
      },
      // immediate:true,//立即侦听
      deep: true, //深度侦听(用于侦听对象属性的变化)
    },
  },

  components: { MyHeader, MyMain, MyFooter },
};
</script>

<style></style>
